package com.uni.controllers;

import java.io.IOException;
import java.util.Random;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.multipart.MultipartFile;

import com.uni.db.GenericService;
import com.uni.domain.Course;
import com.uni.domain.File;
import com.uni.domain.Lection;

@Controller
@RequestMapping("/lectionEdit.htm")
@SessionAttributes(types = Lection.class)
public class LectionEdit {

    @Autowired
	@Qualifier("lectionService")
	private GenericService<Lection> lectionService;

    @Autowired
	@Qualifier("courseService")
	private GenericService<Course> courseService;

    @Autowired
	@Qualifier("fileService")
	private GenericService<File> fileService;

    @RequestMapping(method = RequestMethod.GET)
	public String setupForm(@RequestParam(value="id", required=false) Long id,
                         @RequestParam(value="course", required=true) Long idc, ModelMap model, HttpSession session) {
		Lection lection;
		if (id == null || id < 1){
			lection = new Lection();
		} else {
			lection = lectionService.get(id);
		}
        model.addAttribute("lection", lection);
        return "lectionEdit";
	}

	@RequestMapping(method = RequestMethod.POST)
	public String processSubmit(@ModelAttribute Lection lection, @RequestParam("pr")MultipartFile ufile, /*BindingResult result,*/ SessionStatus status, HttpSession session) {
        System.out.println("edit lection");
        if (false/*result.hasErrors()*/) {
			return "lectionEdit";
		} else {
            System.out.println("begin");
            try {
                File file = new File();
                file.setData(ufile.getBytes());
                file.setName("lection" + (new Random().nextInt()));
                file.setContentType(ufile.getContentType());
                fileService.save(file);
                //lection.setPresentation(file);
            } catch (IOException e) {
                e.printStackTrace();
            }

            Course course = (Course)session.getAttribute("course");
            course.addLection(lection);

            courseService.save(course);
            status.setComplete();
            return "redirect:courseView.htm?id=" + course.getId();
        }
	}
}
